import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import { useParams, Link } from 'react-router-dom';
import CourseListABI from "../contract/ABIs/CourseList.json"; // 课程记录列表合约 ABI
import UserListABI from '../contract/ABIs/UserList.json'; // 用户列表合约 ABI
import AdminABI from '../contract/ABIs/Admin.json'; // 管理员合约 ABI
import * as XLSX from 'xlsx'; // 导入 XLSX 库用于解析 Excel 文件
import Admin_creditsNavBar from './nav/Admin_creditsNavBar.js'

import ActivityListAddress from '../contract/ADDRESSes/ActivityListAddress.js'; // 活动列表合约地址
import MaterialListAddress from '../contract/ADDRESSes/MaterialListAddress'; // 材料列表合约地址
import PointsExchangeAddress from "../contract/ADDRESSes/PointsExchangeAddress.js" // 积分兑换合约地址
import CourseListAddress from "../contract/ADDRESSes/CourseListAddress.js" // 课程记录列表合约地址
import UserListAddress from '../contract/ADDRESSes/UserListAddress'; // 用户列表合约地址
// import '../static/indexcss/aacsss.css';
import Head from './nav/Head.js';

const Admin_addStudents = () => {
    const [web3, setWeb3] = useState(null);
    // 使用 useParams 获取路由参数中的地址信息
    const { address } = useParams();
    const [contractCourseList, setcontractCourseList] = useState(null);
    const [contractUserList, setContractUserList] = useState(null);
    const [contractAdmin, setcontractAdmin] = useState(null);
    const [isAdmin, setIsAdmin] = useState(false);

    // 学生信息数组结构
    const [students, setStudents] = useState([]);


    useEffect(() => {
        async function init() {
            // 连接到以太坊网络
            if (window.ethereum) {
                const web3Instance = new Web3(window.ethereum);
                try {
                    // 请求用户授权
                    await window.ethereum.enable();
                    setWeb3(web3Instance);

                    // 创建课程记录合约实例
                    const courseListInstance = new web3Instance.eth.Contract(
                        CourseListABI,
                        CourseListAddress
                    );
                    setcontractCourseList(courseListInstance);

                    // 创建用户列表合约实例
                    const userListInstance = new web3Instance.eth.Contract(
                        UserListABI,
                        UserListAddress
                    );
                    setContractUserList(userListInstance);

                    // 创建管理员合约实例
                    const adminInstance = new web3Instance.eth.Contract(
                        AdminABI,
                        address
                    );
                    setcontractAdmin(adminInstance);

                    // 获取当前用户的以太坊账户地址
                    const accounts = await web3Instance.eth.getAccounts();
                    const currentAddress = accounts[0];
                    // 获取管理员合约的 owner 地址
                    const ownerAddress = await adminInstance.methods.getOwner().call();
                    // 检查当前账户是否是管理员本人
                    setIsAdmin(currentAddress === ownerAddress);
                } catch (error) {
                    console.error(error);
                }
            } else {
                console.error('请安装以太坊浏览器插件，如 MetaMask');
            }
        }
        init();
    }, [address]);


    // 解析上传的 Excel 文件并添加学生信息到数组中
    const handleFileUpload = (e) => {
        const file = e.target.files[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = (evt) => {
            const data = evt.target.result;
            const workbook = XLSX.read(data, { type: 'binary' });
            const sheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[sheetName];
            const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
            // 提取学生信息并添加到学生信息数组中
            setStudents(jsonData.slice(1)); // Skip header row
        };
        reader.readAsBinaryString(file);
    };

    // 注册用户
    const CreateUser = async () => {
        if (contractUserList) {
            try {
                const accounts = await web3.eth.getAccounts();
                const fromAddress = accounts[0];
                const batchSize = 100; // 每批次添加的学生数量
                const totalStudents = students.length;
                let currentIndex = 0;
                // 循环添加学生数据
                while (currentIndex < totalStudents) {
                    const batchStudents = students.slice(currentIndex, currentIndex + batchSize);
                    const realNamesBatch = batchStudents.map(student => student[0]);
                    const idNumbersBatch = batchStudents.map(student => student[1].toString());
                    const studentIDNumbersBatch = batchStudents.map(student => student[2].toString());
                    const classNumbersBatch = batchStudents.map(student => student[3].toString());
                    const educationalLevelsBatch = batchStudents.map(student => student[4]);
                    const gradeLevelsBatch = batchStudents.map(student => student[5]);
                    const nowPointsBatch = batchStudents.map(student => student[6]);
                    const nowCreditsBatch = batchStudents.map(student => student[7]);
                    const gendersBatch = batchStudents.map(student => student[8]);
                    const phonesBatch = batchStudents.map(student => student[9].toString());
                    const passwordsBatch = batchStudents.map(student => student[10].toString());
                    const accountAddressesBatch = batchStudents.map(student => student[11]);

                    console.log("fromAddress:", fromAddress, "Input:", realNamesBatch, idNumbersBatch, studentIDNumbersBatch, classNumbersBatch, educationalLevelsBatch, gradeLevelsBatch, nowPointsBatch, nowCreditsBatch, gendersBatch, phonesBatch, passwordsBatch, accountAddressesBatch);
                    await contractUserList.methods.createUser(
                        ActivityListAddress,
                        MaterialListAddress,
                        PointsExchangeAddress,
                        CourseListAddress,
                        accountAddressesBatch, // Pass account addresses as ownerAccount
                        batchStudents.map((student, index) => ({
                            realName: realNamesBatch[index],
                            idNumber: idNumbersBatch[index],
                            studentIDNumber: studentIDNumbersBatch[index],
                            classNumber: classNumbersBatch[index],
                            educationalLevel: educationalLevelsBatch[index],
                            gradeLevel: gradeLevelsBatch[index],
                            nowPoint: nowPointsBatch[index],
                            nowCredit: nowCreditsBatch[index],
                            gender: gendersBatch[index],
                            phone: phonesBatch[index],
                            password: passwordsBatch[index]
                        }))
                    ).send({ from: fromAddress });

                    currentIndex += batchSize;
                }
                alert("添加成功")
            } catch (error) {
                console.error(error);
                alert("添加失败")
            }
        }
    };


    return (
        <div>
            {/* 如果当前账户不是管理员，则显示提示信息 */}
            {!isAdmin && (<div>您没有权限访问此页面。</div>)}

            {/* 管理员界面 */}
            {isAdmin && (
                <div>
                    <Admin_creditsNavBar address={address} />
                    <main className="page hire-me-page">
                        <section className="portfolio-block hire-me">
                            <div className="foreground-component">
                                <Eye />
                                <div className="container">
                                    <div className="border rounded border-0 shadow-lg p-3 p-md-5"
                                        data-bs-theme="light"
                                        style={{
                                            backgroundColor: 'rgba(36, 36, 41, 0.6)'
                                        }}
                                    >

                                        <h1>批量注册用户</h1>
                                        <div class="mb-3">

                                            {/* 添加上传 Excel 文件的表单 */}
                                            <input type="file" accept=".xlsx, .xls" onChange={handleFileUpload} />

                                            <div className="mb-3 mt-4">
                                                <button className="btn btn-primary btn-lg d-block w-100" onClick={CreateUser}>注册</button>
                                            </div>

                                        </div>
                                    </div>
                                </div>
                            </div>
                        </section>
                    </main>
                </div>
            )}
        </div>
    );
}

export default Admin_addStudents;